<?php

namespace App\Admin\Controllers;

use App\Admin\Metrics\Examples;
use App\Http\Controllers\Controller;
use App\Models\AdminRoleUser;
use App\Models\ProcessesArchive;
use App\Models\StopReworkReason;
use App\Models\UserProcess;
use App\Models\WorkOrderDispatch;
use Dcat\Admin\Models\Administrator;
use App\Models\Brand;
use App\Models\Car;
use App\Models\ComponentMaintenance;
use App\Models\User;
use App\Models\WorkOrder;
use App\Models\Workshop;
use Dcat\Admin\Admin;
use Dcat\Admin\Http\Controllers\Dashboard;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class HomeController extends Controller
{
    public function index(Content $content)
    {
        if (isset($_GET['selected_workshop'])) {
            $user_workshop_id = $_GET['selected_workshop'];

            session(['workshop_id' => $user_workshop_id]);
        } else {
            if (session('workshop_id')) {
                $user_workshop_id = session('workshop_id');
            } else {
                $user_workshop_id = Auth::guard('admin')->user()->workshop_id;

                session(['workshop_id' => $user_workshop_id]);
            }
        }

        Admin::disablePjax();
        // 使用时间戳防止缓存
        $timestamp = time();

        Admin::js('js/vue.js?t='.$timestamp);
        Admin::css('css/admin/index.css?t='.$timestamp);
        Admin::js('js/admin/index.js?t='.$timestamp);
        Admin::js('js/axios.min.js?t='.$timestamp);
        Admin::js('js/element.js?t='.$timestamp);
        Admin::css('css/element.css?t='.$timestamp);

        //车间
        $work_shop = Workshop::where('status', DEFAULT_TRUE)->get()->toArray();

        //汽车品牌
        $brand = Brand::where('status', DEFAULT_TRUE)->get();

        $user = Administrator::whereHas('roles', function($query) use($user_workshop_id) {
            $query->where('role_id', 3);
        })->where('workshop_id', $user_workshop_id)->get();

        $keyword = '';

        if (isset($_GET['order_search'])) {
            $keyword = $_GET['order_search'];
        }

        $roles = Auth::guard('admin')->user()->roles;

        $roles_type = '';

        if ($roles) {
            foreach ($roles as $key => $value) {
                $roles_type = $value->id;
            }
        }

        $work_order = WorkOrder::whereBetween('status', [0, 16])
            ->where('workshop_id', $user_workshop_id)
            ->where('car_number', 'like', "%{$keyword}%")
            ->whereOr('user_name', 'like', "%{$keyword}%")
            ->orderBy('id', 'desc')
            ->get();

        if ($work_order) {
            foreach ($work_order as $key => &$value) {
                $value['brand_title'] = $value->brand->title;
                $value['car_title'] = $value->car->title;
                $value['service_advisor_name'] = $value->serviceAdvisor->name;
                $value['is_accident'] = $value['is_accident'] == 1 ? true : false;
                $value['is_appointment'] = $value['is_appointment'] == 1 ? true : false;
                $value['is_pre_spray'] = $value['is_pre_spray'] == 1 ? true : false;
                $value['is_return'] = $value['is_return'] == 1 ? true : false;
                $value['is_self_pay'] = $value['is_self_pay'] == 1 ? true : false;
                $value['is_urgent'] = $value['is_urgent'] == 1 ? true : false;
                $value['showButtons'] = false;

                $processes_archives = ProcessesArchive::where('sort', $value['status'])->first();

                $order_dispatch = WorkOrderDispatch::where('work_order_id', $value['id'])
                    ->where('processes_archives_id', $processes_archives->id)
                    ->first();

                if ($order_dispatch) {
                    $value['dispatch_id'] = $order_dispatch->id;
                    $value['manager'] = $order_dispatch->user_name;
                    $value['wait_time'] = formatTimeDifference($order_dispatch->created_at, date('Y-m-d H:i:s'));
                }

                switch ($value['status']) {
                    case '0':
                        $order['pending'][] = $value;
                        break;
                    case '1':
                        $order['waiting_disassembly'][] = $value;
                        break;
                    case '2':
                        $order['disassembly'][] = $value;
                        break;
                    case '3':
                        $order['waiting_shaping'][] = $value;
                        break;
                    case '4':
                        $order['shaping'][] = $value;
                        break;
                    case '5':
                        $order['waiting_priming'][] = $value;
                        break;
                    case '6':
                        $order['priming'][] = $value;
                        break;
                    case '7':
                        $order['waiting_painting'][] = $value;
                        break;
                    case '8':
                        $order['painting'][] = $value;
                        break;
                    case '9':
                        $order['waiting_reassembly'][] = $value;
                        break;
                    case '10':
                        $order['reassembly'][] = $value;
                        break;
                    case '11':
                        $order['waiting_polishing'][] = $value;
                        break;
                    case '12':
                        $order['polishing'][] = $value;
                        break;
                    case '13':
                        $order['waiting_electrical'][] = $value;
                        break;
                    case '14':
                        $order['electrical'][] = $value;
                        break;
                    case '15':
                        $order['inspection'][] = $value;
                        break;
                    case '16':
                        $order['settlement'][] = $value;
                        break;
                }
            }
        }

        $counts['pending'] = isset($order['pending']) ? count($order['pending']) : 0;
        $counts['disassembly'] = isset($order['disassembly']) ? count($order['disassembly']) : 0;
        $counts['waiting_disassembly'] = isset($order['waiting_disassembly']) ? count($order['waiting_disassembly']) : 0;
        $counts['shaping'] = isset($order['shaping']) ? count($order['shaping']) : 0;
        $counts['waiting_shaping'] = isset($order['waiting_shaping']) ? count($order['waiting_shaping']) : 0;
        $counts['priming'] = isset($order['priming']) ? count($order['priming']) : 0;
        $counts['waiting_priming'] = isset($order['waiting_priming']) ? count($order['waiting_priming']) : 0;
        $counts['painting'] = isset($order['painting']) ? count($order['painting']) : 0;
        $counts['waiting_painting'] = isset($order['waiting_painting']) ? count($order['waiting_painting']) : 0;
        $counts['reassembly'] = isset($order['reassembly']) ? count($order['reassembly']) : 0;
        $counts['waiting_reassembly'] = isset($order['waiting_reassembly']) ? count($order['waiting_reassembly']) : 0;
        $counts['polishing'] = isset($order['polishing']) ? count($order['polishing']) : 0;
        $counts['waiting_polishing'] = isset($order['waiting_polishing']) ? count($order['waiting_polishing']) : 0;
        $counts['electrical'] = isset($order['electrical']) ? count($order['electrical']) : 0;
        $counts['waiting_electrical'] = isset($order['waiting_electrical']) ? count($order['waiting_electrical']) : 0;
        $counts['inspection'] = isset($order['inspection']) ? count($order['inspection']) : 0;
        $counts['settlement'] = isset($order['settlement']) ? count($order['settlement']) : 0;

        if (in_array(Auth::guard('admin')->user()->id, systemUserIds())) {
            $permission_status = 1;
        } else {
            $permission_status = 0;
        }

        return $content
            ->body(view('admin.index', [
                'modules' => $this->getModules(),
                'counts' => $counts,
                'timestamp' => $timestamp,
                'work_shop' => $work_shop,
                'brand' => $brand,
                'user' => $user,
                'order' => $order ?? '',
                'user_workshop_id' => $user_workshop_id,
                'processCounts' => $this->getProcessCounts(),
                'roles_type' => $roles_type,
                'permission_status' => $permission_status
            ]));
    }

    protected function getModules()
    {
        return [
            ['name' => 'disassembly', 'title' => '钣金拆解', 'type' => 'double'],
            ['name' => 'shaping', 'title' => '钣金整形', 'type' => 'double'],
            ['name' => 'priming', 'title' => '油漆做底', 'type' => 'double'],
            ['name' => 'painting', 'title' => '喷漆', 'type' => 'double'],
            ['name' => 'reassembly', 'title' => '钣金装复', 'type' => 'double'],
            ['name' => 'polishing', 'title' => '抛光', 'type' => 'double'],
            ['name' => 'electrical', 'title' => '机电装配', 'type' => 'double']
        ];
    }

    protected function getProcessCounts()
    {
        $user_workshop_id = session('workshop_id');

        $in_factory_count = WorkOrder::whereBetween('status', [0, 16])
            ->where('workshop_id', $user_workshop_id)
            ->count();

        $in_production_count = WorkOrder::whereBetween('status', [1, 15])
            ->where('workshop_id', $user_workshop_id)
            ->count();

        $pending_repair_count = WorkOrder::where('status', 0)
            ->where('workshop_id', $user_workshop_id)
            ->count();

        $rework_count = WorkOrder::where('is_return', DEFAULT_TRUE)
            ->whereOr('is_rework', DEFAULT_TRUE)
            ->where('workshop_id', $user_workshop_id)
            ->count();

        $today_start = date('Y-m-d 00:00:00');
        $today_end = date('Y-m-d 23:59:59');

        $today_in_count = WorkOrder::whereBetween('created_at', [$today_start, $today_end])
            ->where('workshop_id', $user_workshop_id)
            ->count();

        $interrupted_count = WorkOrder::where('is_stop', DEFAULT_TRUE)
            ->where('workshop_id', $user_workshop_id)
            ->count();

        $delayed_count = WorkOrder::where('pre_delivery_at', '<' ,date('Y-m-d H:i:s'))
            ->where('status', '<', ORDER_WAIT_PAY)
            ->where('workshop_id', $user_workshop_id)
            ->count();

        $due_today_count = WorkOrder::whereBetween('pre_delivery_at', [$today_start, $today_end])
            ->where('workshop_id', $user_workshop_id)
            ->count();

        $delivered_today_count = WorkOrder::whereBetween('settlement_at', [$today_start, $today_end])
            ->where('workshop_id', $user_workshop_id)
            ->count();

        return [
            ['title' => '在厂车辆', 'count' => $in_factory_count, 'color' => 'info', 'type' => 'in_factory'],
            ['title' => '定损车辆', 'count' => 0, 'color' => 'warning', 'type' => 'damage_assessment'],
            ['title' => '施工车辆', 'count' => $in_production_count, 'color' => 'primary', 'type' => 'in_production'],
            ['title' => '待修车辆', 'count' => $pending_repair_count, 'color' => 'danger', 'type' => 'pending_repair'],
            ['title' => '返工车辆', 'count' => $rework_count, 'color' => 'purple', 'type' => 'rework'],
            ['title' => '今日进厂', 'count' => $today_in_count, 'color' => 'success', 'type' => 'today_in'],
            ['title' => '中断车辆', 'count' => $interrupted_count, 'color' => 'pink', 'type' => 'interrupted'],
            ['title' => '延迟交车', 'count' => $delayed_count, 'color' => 'dark', 'type' => 'delayed'],
            ['title' => '今日应交', 'count' => $due_today_count, 'color' => 'teal', 'type' => 'due_today'],
            ['title' => '今日已交', 'count' => $delivered_today_count, 'color' => 'indigo', 'type' => 'delivered_today'],
        ];
    }

    public function brand(Request $request)
    {
        $param = $request->all();

        $where = [];

        if ($param) {
            $where[] = ['title', 'like', "%{$param['q']}%"];
        }

        //汽车品牌
        $brand = Brand::where($where)->where('status', DEFAULT_TRUE)->get();

        return $brand;
    }

    public function car(Request $request)
    {
        $param = $request->all();

        $where = [];

        if ($param) {
            $where[] = ['title', 'like', "%{$param['q']}%"];
            $where['brand_id'] = $param['brand_id'];
        }

        //汽车品牌
        $brand = Car::where($where)->where('status', DEFAULT_TRUE)->get();

        return $brand;
    }

    public function serviceConsultant(Request $request)
    {
        $user = User::whereJsonContains('role_ids', M03_ID)->get();
        dd($user);
    }

    public function componentMaintenance(Request $request)
    {
        $param = $request->all();

        $where = [];

        if ($param) {
            $where['position_type'] = positionType($param['position_type']);
            $where['type'] = componentType($param['type']);
        }

        $component = ComponentMaintenance::where($where)->where('status', DEFAULT_TRUE)->get();

        if ($component) {
            foreach ($component as $key => &$value) {
                $value['damage_level_type'] = 'light';
                $value['ratio'] = 1;
            }
        }

        return $component;
    }

    public function processesArchivesAll(Request $request)
    {
        $processes_archives = ProcessesArchive::where('status', DEFAULT_TRUE)->orderBy('sort', 'asc')->get();

        return successMessage($processes_archives);
    }

    public function reworkAll(Request $request)
    {
        $rework = StopReworkReason::where('status', DEFAULT_TRUE)->where('type', REWORK_REASON)->get();

        return successMessage($rework);
    }

    public function stopAll(Request $request)
    {
        $stop = StopReworkReason::where('status', DEFAULT_TRUE)->where('type', STOP_REASON)->get();

        return successMessage($stop);
    }

    public function technicianAll(Request $request)
    {
        $param = $request->all();

        $user_process = UserProcess::where('workshop_id', session('workshop_id'))->whereJsonContains('processes_archives_ids', $param['id'])->get();

        if ($user_process) {
            foreach ($user_process as $key => &$value) {
                $value['user_name'] = $value->user->name;
                $value['dispatch_count'] = WorkOrderDispatch::where('user_id', $value['user_id'])->where('repair_status', PROCESSES_IN)->count();
            }
        }

        return successMessage($user_process);
    }

}
